package com.sd.nacosdemo.controller;

import java.util.concurrent.TimeUnit;

import com.sd.nacosdemo.Util.RedisUtils;
import com.sd.nacosdemo.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


/**
 * @ClassName RedisController
 * @Description TODO
 * @date 2021/6/23 12:46
 * @Version 1.0
 */
@RestController
public class RedisController {

    public static final Logger log = LoggerFactory.getLogger(RedisController.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping(value = "/t/{id}")
    @ResponseBody
    public Object hello(@PathVariable(value = "id") String id){
        //查询缓存中是否存在
        boolean hasKey = redisUtils.exists(id);
        String str = "";
        if(hasKey){
            //获取缓存
            Object object =  redisUtils.get(id);
            if (object!=null){
                log.info("从缓存获取的数据"+ object);
                str = object.toString();
            }else {
                //从数据库中获取信息
                log.info("从数据库中获取数据");
                str = redisService.selectUsers();

                //数据插入缓存（set中的参数含义：key值，user对象，缓存存在时间10（long类型），时间单位）
                redisUtils.set(id,str,10L,TimeUnit.MINUTES);
                log.info("数据插入缓存" + str);
            }
        }else {
            //从数据库中获取信息
            log.info("从数据库中获取数据");
            str = redisService.selectUsers();
            //数据插入缓存（set中的参数含义：key值，user对象，缓存存在时间10（long类型），时间单位）
            redisUtils.set(id,str,10L,TimeUnit.MINUTES);
            log.info("数据插入缓存" + str);
        }

            return str;
    }

}
